package com.bbx.taxi.client.Activity.Menu;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONObject;

import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.database.Cursor;
import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.LinearLayout;
import android.widget.Toast;
import butterknife.InjectView;

import com.bbx.androidapi.util.ToastUtil;
import com.bbx.api.gclient.GMsg;
import com.bbx.api.sdk.model.official.passanger.Return.Officail_OrderInfo;
import com.bbx.api.sdk.model.official.passanger.Return.OrderList.OfficialOrderList;
import com.bbx.api.sdk.model.passanger.Return.Jmsg.Msgs;
import com.bbx.taxi.client.Activity.Base.BaseBBXActivity;
import com.bbx.taxi.client.Activity.Order.OrderCancelReason;
import com.bbx.taxi.client.Activity.Order.OrderDelete;
import com.bbx.taxi.client.Activity.Order.OrderEvaluationActivity2;
import com.bbx.taxi.client.Activity.Order.OrderUnprocessed;
import com.bbx.taxi.client.Activity.Order.StartServiceActivity;
import com.bbx.taxi.client.Adapter.MessageAdapter;
import com.bbx.taxi.client.Bean.Value;
import com.bbx.taxi.client.Bean.Extra.ExamineMsg;
import com.bbx.taxi.client.Bean.Extra.OrderMsg;
import com.bbx.taxi.client.DB.JmsgDB;
import com.bbx.taxi.client.DB.MyOrder.MyOrderDB;
import com.bbx.taxi.client.DB.Util.DBcolumns;
import com.bbx.taxi.client.Task.OrderDetailTask;
import com.bbx.taxi.client.Task.OrderDetailTask.OnOrderDetailFinishListener;
import com.bbx.taxi.client.widget.Dailog.MyAlertDailog;
import com.bbx.taxi.client.widget.Dailog.MyAlertDailog.onClickLeftListener;
import com.bbx.taxi.client.widget.Dailog.MyAlertDailog.onClickRightListener;
import com.bbx.taxi.official.R;
import com.example.mylistview.pullListView.PullToRefreshLayout;
import com.example.mylistview.pullListView.PullToRefreshLayout.OnRefreshListener;
import com.example.mylistview.pullListView.PullableListView;
import com.example.mylistview.pullListView.PullableListView.OnLoadListener;
import com.example.mylistview.swipemenu.MyListView;
import com.example.mylistview.swipemenu.MyListView.OnMenuItemClickListener;
import com.example.mylistview.swipemenu.SwipeMenu;

public class MessageActivity extends BaseBBXActivity implements
		OnItemClickListener,OnLoadListener,OnRefreshListener,OnOrderDetailFinishListener {
	@InjectView(R.id.MyListView)
	MyListView mMyListView;
	@InjectView(R.id.pullToRefreshLayout)
	PullToRefreshLayout pullToRefreshLayout;
	@InjectView(R.id.layout_nodata)
	LinearLayout layout_nodata;
	private List<Map<String, String>> list;
	private MessageAdapter mMessageAdapter;
	private MyOrderDB db_myorder;// 我的进行中的订单数据库
	private JmsgDB db_jmsg;
	private int num = 10;

	protected void onCreate(Bundle savedInstanceState) {
		setContentView(R.layout.activity_message);
		super.onCreate(savedInstanceState);
	
	}

	@Override
	protected void initView() {
		setTitle(true,getString(R.string.msg), -1,getString(R.string.empty));
		db_myorder = new MyOrderDB(this);
		db_jmsg = new JmsgDB(this);
		initMyListView();
		initswipe();
		list = new ArrayList<Map<String, String>>();
		mMessageAdapter = new MessageAdapter(this, list);
		LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		View headerview = inflater.inflate(R.layout.headerview, null);
		//【主要，添加headerview，则在OnItenClick中的Position就会错乱】
		mMyListView.addHeaderView(headerview,null,false);
		mMyListView.setAdapter(mMessageAdapter);
		mMyListView.setOnItemClickListener(this);

	}

	@Override
	protected void initData() {
		onReadDB();
	}

	private void initMyListView() {
		pullToRefreshLayout.setOnRefreshListener(this);
	    mMyListView.setOnLoadListener(this);
	    mMyListView.setHasMoreData(true);
		mMyListView.setEmptyView(layout_nodata);
		

	}

	/**
	 * 初始化ListView的Item菜单
	 */
	public void initswipe() {
        super.initswipe();
		// step 2. listener item click event
		mMyListView.setOnMenuItemClickListener(new OnMenuItemClickListener() {
			@Override
			public void onMenuItemClick(final int position, SwipeMenu menu, int index) {
				// ApplicationInfo item = mAppList.get(position);
				switch (index) {
				case 0:
					final MyAlertDailog dialog = new MyAlertDailog(
							context);
					Resources res = context.getResources();
					dialog.setTitle(res
							.getString(R.string.mydailog_title));
					dialog.setContent(res
							.getString(R.string.mydailog_content_delete));
					dialog.setLeftButtonText(res
							.getString(R.string.mydailog_close));
					dialog.setRightButtonText(res
							.getString(R.string.mydailog_delete));
					if (dialog != null && !dialog.isShowing()) {
						dialog.show();
					}
					dialog.setOnClickLeftListener(new onClickLeftListener() {
						@Override
						public void onClickLeft() {
							dialog.dismiss();
						}
					});
					dialog.setOnClickRightListener(new onClickRightListener() {

						@Override
						public void onClickRight() {
							dialog.dismiss();
							
							db_jmsg.onDelete(list.get(position).get(
									DBcolumns.MESSAGE_ID));
							list.remove(position);
							notifyDataSetChanged(mMessageAdapter);
							Toast.makeText(MessageActivity.this,getString(R.string.del_success),
									Toast.LENGTH_SHORT).show();
							handler.postDelayed(new Runnable() {
								@Override
								public void run() {
									mMyListView.closeMenu();
								}
							}, 200);
						}
					});
					break;

				}
			}
		});
	}

	private void refresh() {
		list.clear();
		onReadDB();
		pullToRefreshLayout.refreshFinish(PullToRefreshLayout.SUCCEED);

	}

	private void load() {
		Cursor c = db_jmsg.onQuery(
				Integer.parseInt(list.get(list.size() - 1).get(
						DBcolumns.MESSAGE_ID)), num);
		c.moveToFirst();
		if (c.getCount() > 0) {
			do {
				Map<String, String> map = new HashMap<String, String>();
				for (int i = 0; i < c.getColumnCount(); i++) {
					map.put(c.getColumnName(i), c.getString(i));
				}
				list.add(map);
			} while (c.moveToNext());
			handler.postDelayed(new Runnable() {
				@Override
				public void run() {
					notifyDataSetChanged(mMessageAdapter);
					mMyListView.setHasMoreData(true);
				}
			}, 200);
		} else {
			mMyListView.setHasMoreData(false);
		}
		c.close();
		db_jmsg.onColse();
		
	}

	/**
	 * 读取数据库数据,判断是否第一次，第一次的话，读取完自动刷新
	 */
	private void onReadDB() {
		list.clear();
		Cursor c = db_jmsg.onQuery(-1, num);
		c.moveToFirst();
		if (c.getCount() > 0) {
			do {
				Map<String, String> map = new HashMap<String, String>();
				for (int i = 0; i < c.getColumnCount(); i++) {
					map.put(c.getColumnName(i), c.getString(i));
				}
				list.add(map);
			} while (c.moveToNext());
		}
		db_jmsg.onColse();
		notifyDataSetChanged(mMessageAdapter);
		
		
		if (list.size() >= num) {
			mMyListView.setHasMoreData(true);
		} else {
			mMyListView.setHasMoreData(false);
		}
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.tv_right:// 清空
			final MyAlertDailog dialog = new MyAlertDailog(
					context);
			Resources res = context.getResources();
			dialog.setTitle(res
					.getString(R.string.mydailog_title));
			dialog.setContent(res
					.getString(R.string.mydailog_content_empty));
			dialog.setLeftButtonText(res
					.getString(R.string.mydailog_close));
			dialog.setRightButtonText(res
					.getString(R.string.mydailog_empty));
			if (dialog != null && !dialog.isShowing()) {
				dialog.show();
			}
			dialog.setOnClickLeftListener(new onClickLeftListener() {
				@Override
				public void onClickLeft() {
					dialog.dismiss();
				}
			});
			dialog.setOnClickRightListener(new onClickRightListener() {

				@Override
				public void onClickRight() {
					dialog.dismiss();
					db_jmsg.onDelete();
					list.clear();
					ToastUtil.showToast(context, R.string.empty_success);
					notifyDataSetChanged(mMessageAdapter);
				}
			});
			break;
		default:
			super.onClick(v);
			break;
		}
	}

	@Override
	public void onNotify(int type,JSONObject jb,Msgs.Data msgs_data){
		handler.sendEmptyMessage(0);
		super.onNotify(type, jb,msgs_data);
	}

	private Handler handler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case 0:
				refresh();
				break;
			}
		};
	};
	public void notifyDataSetChanged(BaseAdapter adapter) {
		adapter.notifyDataSetChanged();
		onisShowNodata(adapter);
	}

	public void onisShowNodata(BaseAdapter adapter) {
//		if (adapter.getCount() == 0) {
//			layout_nodata.setVisibility(View.VISIBLE);
//		} else {
//			layout_nodata.setVisibility(View.GONE);
//		}
	}
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if(requestCode==this.requestCode){
			onReadDB();
		}
		super.onActivityResult(requestCode, resultCode, data);
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		// TODO 【修正有Header的ListView的position的BUG】  
		int headerViewsCount = mMyListView.getHeaderViewsCount();//得到header的总数量  
		//【得到新的修正后的position】  
		int newPosition = position - headerViewsCount; 
		
		int type=0;
		try{
			 type=Integer.parseInt(list.get(newPosition).get(DBcolumns.MESSAGE_TYPE));
		}
		catch(Exception e){}	
		switch(type){
		    //不可以点击
			case GMsg.OFFICAIL_AA:break;
			//可以点击
			default:
				String order_id = (list.get(newPosition).get(DBcolumns.MESSAGE_ORDER_ID));
				ArrayList<OfficialOrderList> list_all= new ArrayList<OfficialOrderList>();
				list_all.addAll(db_myorder.onReadDB(this,
						MyOrderActivity.num_ing));
				//写入已读状态
				try{
					int message_id=Integer.parseInt(list.get(newPosition).get(DBcolumns.MESSAGE_ID));
					db_jmsg.onUpdate(message_id,Value.MSG_READ);
				}
				catch(Exception e){}	
				for (int i = 0; i < list_all.size(); i++) {
					if (list_all.get(i).getOrder_id().equals(order_id)) {
						String audit_status=list_all.get(i).getAudit_status();
						int status=Integer.parseInt(list_all.get(i).getOrder_status());
						if(status==Value.ORDER_STATUS_UNTREATED&&audit_status!=null&&audit_status.equals(Value.STATUS_AUDIT_NO)){
							OrderUnprocessed.setOrder(list_all.get(i),list_all.get(i).getOrder_id());
							context.startActivity(new Intent(context,OrderUnprocessed.class)
							.putExtra(ExamineMsg.EXAMINE_TYPE,ExamineMsg.TYPE_OF)
							.putExtra(ExamineMsg.EXAMINE_STATUS,ExamineMsg.STATUS_NO));
							return;
						}else if(status==Value.ORDER_STATUS_UNTREATED&&audit_status!=null&&audit_status.equals(Value.STATUS_AUDIT_NOPASS)){
							OrderUnprocessed.setOrder(list_all.get(i),list_all.get(i).getOrder_id());
							context.startActivity(new Intent(context,OrderUnprocessed.class)
							.putExtra(ExamineMsg.EXAMINE_TYPE,ExamineMsg.TYPE_OF)
							.putExtra(ExamineMsg.EXAMINE_STATUS,ExamineMsg.STATUS_AGAIN));
							return;
						}else{
						if(status<Value.ORDER_STATUS_OFFCAR||
								status==Value.ORDER_STATUS_GAIPAI||
										status==Value.ORDER_STATUS_KF_GAIPAI){
							Intent intent = new Intent(context, StartServiceActivity.class);
							intent.putExtra(OrderMsg.extra_type, 1);
							intent.putExtra(OrderMsg.extra_order_id, list_all.get(i).getOrder_id());
							startActivityForResult(intent, requestCode);
							return;
						}
						else if(status==Value.ORDER_STATUS_FINISH||status==Value.ORDER_STATUS_OFFCAR){
						Intent intent = new Intent(context,
									OrderEvaluationActivity2.class);
							intent.putExtra(OrderMsg.order_id_finish, list_all.get(i).order_id);
							intent.putExtra(OrderMsg.finish_type,
									OrderMsg.finish_all);
							startActivityForResult(intent, requestCode);
							return;
						}
						else if(status==Value.ORDER_STATUS_CANCEL||status==Value.ORDER_STATUS_KF_CANCEL){
							Intent intent = new Intent(context,
									OrderCancelReason.class);
							intent.putExtra(OrderMsg.extra_order_id, list_all.get(i).order_id);
							startActivityForResult(intent, requestCode);
							return;
						}

						else if(status==Value.ORDER_STATUS_DELETE){
							Intent intent = new Intent(context,
									OrderDelete.class);
							startActivity(intent);
							return;
						}
						else{
						Intent intent = new Intent(context,
									OrderEvaluationActivity2.class);
							intent.putExtra(OrderMsg.order_id_finish, list_all.get(i).order_id);
							startActivityForResult(intent, requestCode);
							return;
						  }
						}
					}
				}
				//找不到该订单这获取网络数据
				OrderDetailTask.getInstance(context, mApplication, order_id).setOnOrderDetailFinishListener(this);
				break;
		}
	}

	@Override
	public void onRefresh(PullToRefreshLayout pullToRefreshLayout) {
		refresh();
	}

	@Override
	public void onLoad(PullableListView pullableListView) {
		load();
	}

	@Override
	public void onOrderDetailFinish(Officail_OrderInfo mOfficail_OrderInfo) {
		if(mOfficail_OrderInfo!=null){
		String audit_status=mOfficail_OrderInfo.getInfo().getAudit_status();
		int status=Integer.parseInt(mOfficail_OrderInfo.getInfo().getOrder_status());
		String order_id=mOfficail_OrderInfo.getInfo().getOrder_id();
		if(status==Value.ORDER_STATUS_UNTREATED&&audit_status!=null&&audit_status.equals(Value.STATUS_AUDIT_NO)){
			OrderUnprocessed.setOrder(mOfficail_OrderInfo.getInfo(),mOfficail_OrderInfo.getInfo().getOrder_id());
			context.startActivity(new Intent(context,OrderUnprocessed.class)
			.putExtra(ExamineMsg.EXAMINE_TYPE,ExamineMsg.TYPE_OF)
			.putExtra(ExamineMsg.EXAMINE_STATUS,ExamineMsg.STATUS_NO));
			return;
		}else if(status==Value.ORDER_STATUS_UNTREATED&&audit_status!=null&&audit_status.equals(Value.STATUS_AUDIT_NOPASS)){
			OrderUnprocessed.setOrder(mOfficail_OrderInfo.getInfo(),mOfficail_OrderInfo.getInfo().getOrder_id());
			context.startActivity(new Intent(context,OrderUnprocessed.class)
			.putExtra(ExamineMsg.EXAMINE_TYPE,ExamineMsg.TYPE_OF)
			.putExtra(ExamineMsg.EXAMINE_STATUS,ExamineMsg.STATUS_AGAIN));
			return;
		}else{
		if(status<Value.ORDER_STATUS_OFFCAR||
				status==Value.ORDER_STATUS_GAIPAI||
				status==Value.ORDER_STATUS_KF_GAIPAI){
			Intent intent = new Intent(context, StartServiceActivity.class);
			intent.putExtra(OrderMsg.extra_type, 1);
			intent.putExtra(OrderMsg.extra_order_id, order_id);
			startActivityForResult(intent, requestCode);
			return;
		}
		else if(status==Value.ORDER_STATUS_FINISH||status==Value.ORDER_STATUS_OFFCAR){
		Intent intent = new Intent(context,
					OrderEvaluationActivity2.class);
			intent.putExtra(OrderMsg.order_id_finish,order_id);
			intent.putExtra(OrderMsg.finish_type,
					OrderMsg.finish_all);
			startActivityForResult(intent, requestCode);
			return;
		}
		else if(status==Value.ORDER_STATUS_CANCEL||status==Value.ORDER_STATUS_KF_CANCEL){
			Intent intent = new Intent(context,
					OrderCancelReason.class);
			intent.putExtra(OrderMsg.extra_order_id, order_id);
			startActivityForResult(intent, requestCode);
			return;
		}
		else if(status==Value.ORDER_STATUS_DELETE){
			Intent intent = new Intent(context,
					OrderDelete.class);
			startActivity(intent);
			return;
		}
		else{
		Intent intent = new Intent(context,
					OrderEvaluationActivity2.class);
			intent.putExtra(OrderMsg.order_id_finish, order_id);
			startActivityForResult(intent, requestCode);
			return;
	    	}
		}
	   }
	}
}
